package dao

import (
	"context"
	"gitee.com/chunanyong/zorm"
	"gitee.com/xinshortlink/internal/dal/db/model"
	"gitee.com/xinshortlink/internal/dto/resp/bizerr"
	"go.uber.org/zap"
)

type ShortRouteDao struct {
	logger *zap.Logger
}

func NewShortRouteDao(logger *zap.Logger) *ShortRouteDao {
	return &ShortRouteDao{logger: logger}
}

// FindGidByShortId 查询 gid
// 分表路由
func (d *ShortRouteDao) FindGidByShortId(ctx context.Context, shortId string) (int64, error) {
	e := &model.ShortRouteStruct{
		ShortId: shortId,
	}

	finder := zorm.NewSelectFinder(e.GetTableName()).Append("WHERE short_id = ?", shortId)
	has, err := zorm.QueryRow(ctx, finder, e)
	if err != nil {
		return 0, err
	}
	if !has {
		return 0, nil
	}

	return e.Gid, nil
}

// Create 创建路由
func (d *ShortRouteDao) Create(ctx context.Context, gid int64, shortId string) error {
	_, err := zorm.Insert(ctx, &model.ShortRouteStruct{
		ShortId: shortId,
		Gid:     gid,
	})
	if err != nil {
		return bizerr.New(bizerr.DB, "创建短链接路由出错", err)
	}
	return err
}
